package org.vacoor.xqq.reply.impl;

import com.fasterxml.jackson.databind.JsonNode;
import org.vacoor.nothing.common.json.Jacksons;
import org.vacoor.xqq.reply.ResolveException;
import org.vacoor.xqq.reply.ResponseResolver;

/**
 */
public abstract class JsonResolver<T> implements ResponseResolver<T> {

    @Override
    public T resolveReply(final String reply) throws ResolveException {
        JsonNode replyJson = Jacksons.readTree(reply);
        if (replyJson == null) {
            throw new ResolveException("Can not be resolve reply to json:" + reply);
        }
        return doResolve(replyJson);
    }

    protected T doResolve(JsonNode json) {
        int retcode = json.get("retcode").asInt(-1);
        JsonNode result = json.get("result");
        if (0 != retcode || result == null) {
            return null;
        }
        return doResolveResult(result);
    }

    protected abstract T doResolveResult(JsonNode result);

}
